﻿using System.Text.RegularExpressions;
using System.Windows;
using GalaSoft.MvvmLight.Command;
using ValidationSample.Validations;

namespace ValidationSample
{
    public class MainViewModel : ViewModelBaseEx
    {
        public MainViewModel()
        {
            Submit = new RelayCommand(SubmitAction);
            NameValidator = new Validator(NameValidation);
            PhoneValidator = new Validator(PhoneValidation);

            Validators.Add(NameValidator);
            Validators.Add(PhoneValidator);
        }

        private string PhoneValidation(string arg)
        {
            if (string.IsNullOrWhiteSpace(arg))
                return "Phone should not be empty";

            Regex regexObj = new Regex(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$");

            if (!regexObj.IsMatch(arg))
                return "Phone is in incorrect format";
            return string.Empty;
        }

        private string NameValidation(string arg)
        {
            if (string.IsNullOrWhiteSpace(arg))
                return "Name should not be empty";
            if (arg.Length < 3)
                return "Name should be greater than 2 symbols";
            if (arg.Length > 19)
                return "Name should be less than 20 symbols";
            return string.Empty;
        }

        private void SubmitAction()
        {
            if (ValidateAll())
            {
                MessageBox.Show("Done!");
            }
        }

        public RelayCommand Submit { get; private set; }

        public Validator NameValidator { get; private set; }

        private string name;
        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                RaisePropertyChanged("Name");
            }
        }

        public Validator PhoneValidator { get; private set; }

        private string phone;
        public string Phone
        {
            get { return phone; }
            set
            {
                phone = value;
                RaisePropertyChanged("Phone");
            }
        }
    }
}
